import { ShowTypeEnum } from '@/enums/auth';
import { notification } from 'antd';
import { extend } from 'umi-request';

const codesMap: Record<number, string> = {
  // 4xx 客户端错误
  400: '错误请求',
  401: '未授权',
  402: '需要付款',
  403: '禁止访问',
  404: '未找到',
  408: '请求超时',
  409: '令牌无效或已过期',
  423: '已锁定',
  425: '过早请求',
  429: '请求过多',
  451: '因法律原因不可用',
  460: '缺少客户端ID',

  // 5xx 服务端错误
  500: '服务器内部错误',
  501: '未实现',
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时',
  505: '版本不支持',
  507: '存储空间不足',
  508: '检测到循环',
  509: '超出带宽限制',
};

// 创建请求实例
const request = extend({
  timeout: 10000,
});

// 请求拦截器：添加认证
request.interceptors.request.use((url, options) => {
  const token = localStorage.getItem('access_token');

  // 默认 headers 配置
  const defaultHeaders = {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };

  // 如果 options 中指定了 skipDefaultHeaders，则不使用默认 headers
  const headers = options.skipDefaultHeaders
    ? options.headers
    : { ...defaultHeaders, ...options.headers };

  return {
    url: `${API_URL}${url}`,
    options: {
      ...options,
      headers,
    },
  };
});

// 响应拦截器：处理业务错误
request.interceptors.response.use(async (response): Promise<Response> => {
  const { status }: any = response;

  if (status !== 200) {
    const { code = 555, msg, showType } = await response.clone().json();

    const message = `请求状态码 ${response.status}`;
    const duration = 8;
    let description;

    if (response.status === 400) {
      description = msg || '错误请求';
    }
    if (response.status === 401) {
      if (code >= 1000) {
        //认证错误场景
        description = msg || '认证错误';
      } else {
        description = '请先登录';
      }
    }
    if (response.status === 403) {
      description = '无访问权限';
    }
    if (response.status === 404) {
      description = '请求资源不存在';
    }
    if (response.status === 409) {
      description = '令牌过期';
      window.location.href = '/turing/user/login';
    }
    if (response.status === 500) {
      description = '服务异常，请稍后再试';
    }
    if (response.status === 502) {
      description = '网关异常，请稍后再试';
    }
    if (response.status === 503) {
      description = '服务不可用，请稍后再试';
    }
    if (response.status === 504) {
      description = '网关超时，请稍后再试';
    }
    if (showType !== ShowTypeEnum.SILENT && code !== 401) {
      notification.error({
        message,
        description,
        duration,
      });
    }

    return Promise.reject(description);
  }
  const { access_token } = await response.clone().json();
  if (access_token) {
    return response;
  }
  const { code = 555, msg, showType } = await response.clone().json();

  if (code > 200 && code <= 555) {
    const description = `${codesMap[code]}:${msg}` || '未知错误';
    if (showType !== ShowTypeEnum.SILENT) {
      notification.error({
        message: `业务错误 ${code}`,
        description,
      });
    }
    return Promise.reject(description);
  }

  return response;
});

// 带认证的 POST 请求
export async function post<T>(url: string, data?: any) {
  return request<T>(`${url}.admin`, {
    method: 'POST',
    data,
  });
}

export async function postAuth(params: any) {
  const base64AuthString = 'Y2hhb3MtY2xpZW50OnNlY3JldA==';
  const formData = new URLSearchParams(params);

  return request(`/auth/oauth2/token`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${base64AuthString}`,
    },
    data: formData.toString(),
    skipDefaultHeaders: true,
  });
}
